package com.my.websocket;

//WebSocket服务端，用于向浏览器实时随送车位状态，相当于WebSocket的Controller
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

//WebSocketClient工具类，存储所有已连接的WebSocket Session，并支持向所有客户端广播推送信息
public class WebSocketClients {

     // concurrent包的线程安全Map，用来存放每个客户端对应的MyWebSocket对象
    public static Map<String, WebSocketClient> webSocketClientMap = new ConcurrentHashMap<>();

    public static void addClient(WebSocketClient client) {
        String id = client.getSession().getId();
        webSocketClientMap.put(id, client);
    }

    public static void removeClient(WebSocketClient client) {
        String id = client.getSession().getId();
        webSocketClientMap.remove(id);
    }

    //获取在线客户端数
    public static int getOnlineCount() {
        return webSocketClientMap.size();
    }

    //向所有websocket客户端推送消息
    public static void boardCast(String message) {
        Set<Map.Entry<String, WebSocketClient>> entries = webSocketClientMap.entrySet();
        for (Map.Entry<String, WebSocketClient> clientEntry : entries) {
            WebSocketClient client = clientEntry.getValue();
            try {
                client.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
